﻿using System;
using System.Collections.Generic;

namespace NodeEditor
{
    public static class BFSHelper
    {
        public static T[] BFSForEach<T>(this List<T> array, T start, Func<T, T, bool> filter)
        {
            return BFSForEach(array.ToArray(), start, filter);
        }
        public static T[] BFSForEach<T>(this T[] array, T start, Func<T, T, bool> filter)
        {
            var count = array.Length;
            List<T> results = new List<T>();
            Queue<T> queue = new Queue<T>();
            HashSet<T> visited = new HashSet<T>();
            queue.Enqueue(start);
            visited.Add(start);
            while (queue.Count != 0)
            {
                var _ = queue.Dequeue();
                for (var i = 0; i < count; i++)
                {
                    var __ = array[i];
                    if(!visited.Contains(__) && filter(_,__))
                    {
                        queue.Enqueue(__);
                        visited.Add(__);
                    }
                }
                results.Add(_);
            }

            return results.ToArray();
        }
    }
}